package com.edu.marker.activities;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import com.edu.marker.R;
import com.edu.marker.pojo.UserInfo;
import com.edu.marker.task.WSAPI;
import com.edu.marker.task.WSAPI.WSACTION;
import com.edu.marker.task.WSTask.TaskListener;
import com.edu.marker.utils.Constants;
import com.edu.marker.utils.LogUtils;
import com.edu.marker.utils.Prefs;
import com.edu.marker.utils.ToastUtils;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;

public class LoginActivity extends Activity {
	final LogUtils L = LogUtils.getLog(LoginActivity.class);
	private  SharedPreferences mPref;
	private ImageView mAccountImage;
	private ImageView mPwdImage;
	private EditText mAccount;
	private EditText mPassword;
	private CheckBox mRemPwd;
	private Button mBtnLogin;
	private String mAccountStr;
	private String mPasswordStr;
	private boolean isRembered;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		setupViews();
	}
	
	private void setupViews(){
		mPref = PreferenceManager.getDefaultSharedPreferences
				(LoginActivity.this);
		isRembered = mPref.getBoolean(Constants.LOGINED, true);
				
		mAccountImage = (ImageView)findViewById(R.id.login_imageview_id);
		mPwdImage = (ImageView)findViewById(R.id.login_imageview_pwd);
		mAccount = (EditText)findViewById(R.id.login_edit_id);
		mPassword = (EditText)findViewById(R.id.login_edit_pwd);
		mRemPwd = (CheckBox)findViewById(R.id.login_checkbox);
		mBtnLogin = (Button)findViewById(R.id.login_button);
		
		mAccountImage.setOnClickListener(mClicker);
		mPwdImage.setOnClickListener(mClicker);
		mBtnLogin.setOnClickListener(mClicker);
		
		mAccount.addTextChangedListener(mAccountWatcher);
		mPassword.addTextChangedListener(mPwdWatcher);
		
		mAccount.setOnFocusChangeListener(mChanger);
		mPassword.setOnFocusChangeListener(mChanger);
		
		mRemPwd.setOnCheckedChangeListener(mChecker);
		
		if(isRembered) {
			mRemPwd.setChecked(true);
		} else {
			mRemPwd.setChecked(false);
		}
		
		remmberLogin();
	}
	
	/******************************private apis****************************************/
	private void login(){
		mAccountStr =  mAccount.getText().toString();
		mPasswordStr =  mPassword.getText().toString();
		//mAccountStr =  "tjb_dongfarong";
		//mPasswordStr =  "123456";
		if("".equals(mAccountStr)||mAccountStr==null){
			ToastUtils.failed(LoginActivity.this, "101");
		}else if("".equals(mPasswordStr)||mPasswordStr==null){
			ToastUtils.failed(LoginActivity.this, "102");
		}else{
			final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			params.add(new BasicNameValuePair("serverUrl", Constants.loginUrl));
			params.add(new BasicNameValuePair("method", "onLogin"));
			params.add(new BasicNameValuePair("account", mAccountStr.trim()));
			params.add(new BasicNameValuePair("passWord", mPasswordStr.trim()));
			WSAPI.doRequest(this, mTaskListener, params, WSACTION.ACT_LOGIN);
		}
	}
	
	private void remmberLogin() {
		if(mRemPwd.isChecked() && isRembered) {
			final String userName = mPref.getString(Constants.USERNAME , "");
			final String userPass = mPref.getString(Constants.ACCOUNT , "");
			if(!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(userPass)) {
				mAccount.setText(userName);
				mPassword.setText(userPass);
			}
		}
	}
	
	private final TaskListener mTaskListener = new TaskListener() {
		public void onSuccess(int action, Object result) {
			final UserInfo userInfo = (UserInfo) result; 
			if(userInfo.isResult()) {
				L.d("登陆成功，用户名为："+userInfo.getName());
				
				Prefs.setStrValue(mPref.edit(), Constants.USERNAME, userInfo.getName());
				Prefs.setStrValue(mPref.edit(), Constants.ACCOUNT, mAccountStr.trim());
				
				final Intent intent = new Intent();
				intent.setClass(LoginActivity.this, PaperInfoActivity.class);
				startActivity(intent);
				finish();
			} else {
				ToastUtils.message(LoginActivity.this, userInfo.getErrMessage());
			}
		}

		public void onFailed(int action, String errcode, Exception ex) {
			ToastUtils.failed(LoginActivity.this, ex, getString(R.string.login_faill_err));
		}
	};
	
	private OnClickListener mClicker = new OnClickListener() {
		public void onClick(View v) {
			switch(v.getId()) {
			case R.id.login_imageview_id:
				mAccount.setText(null);
				break;
			case R.id.login_imageview_pwd:
				mPassword.setText(null);
				break;
			case R.id.login_button:
				login();
				break;
			}
		}
	};
	
	private TextWatcher mAccountWatcher = new TextWatcher() {
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			String value = mAccount.getText().toString().trim();
			if (!TextUtils.isEmpty(value)) {
				mAccountImage.setVisibility(View.VISIBLE);
			}else{
				mAccountImage.setVisibility(View.GONE);
			}
		}
		
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
		}
	};
	
	private TextWatcher mPwdWatcher = new TextWatcher() {
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			String value = mPassword.getText().toString().trim();
			if (!TextUtils.isEmpty(value)) {
				mPwdImage.setVisibility(View.VISIBLE);
			}else{
				mPwdImage.setVisibility(View.GONE);
			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
		}
	};
	
	private OnFocusChangeListener mChanger =  new OnFocusChangeListener() {
		public void onFocusChange(View v, boolean hasFocus) {
			switch(v.getId()) {
			case R.id.login_edit_id:
				if(hasFocus){
					final String value = mAccount.getText().toString().trim();
					if (!TextUtils.isEmpty(value)) {
						mAccountImage.setVisibility(View.VISIBLE);
					}
				}else{
					mAccountImage.setVisibility(View.GONE);
				}
				break;
			case R.id.login_edit_pwd:
				if(hasFocus){
					String value = mPassword.getText().toString().trim();
					if (!TextUtils.isEmpty(value)) {
						mPwdImage.setVisibility(View.VISIBLE);
					}
				}else{
					mPwdImage.setVisibility(View.GONE);
				}
				break;
			}
		}
	};
	
	private OnCheckedChangeListener mChecker = new OnCheckedChangeListener() {
		public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
			Prefs.setBoolValue(mPref.edit(), Constants.LOGINED, isChecked);
		}
	};
}
